#!/bin/bash

# RK3588智能表情交互系统 - ARM交叉编译构建脚本
# 使用正点原子ATK-DLRK3588交叉编译工具链

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目配置
PROJECT_NAME="qt_cpp"
BUILD_DIR="build_arm"
PRO_FILE="qt_cpp.pro"

# 交叉编译工具链配置
TOOLCHAIN_PREFIX="aarch64-buildroot-linux-gnu"
TOOLCHAIN_DIR="/opt/atk-dlrk3588-toolchain"
TOOLCHAIN_BIN="$TOOLCHAIN_DIR/bin"
TOOLCHAIN_SYSROOT="$TOOLCHAIN_DIR/aarch64-buildroot-linux-gnu/sysroot"

# Qt交叉编译配置
QT_CROSS_QMAKE="$TOOLCHAIN_BIN/qmake"

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查交叉编译工具链
check_toolchain() {
    print_info "检查ARM交叉编译工具链..."
    
    # 检查工具链目录
    if [ ! -d "$TOOLCHAIN_DIR" ]; then
        print_error "交叉编译工具链未找到: $TOOLCHAIN_DIR"
        print_info "请先安装正点原子ATK-DLRK3588交叉编译工具链"
        print_info "工具链位置: rk3588资料/05、开发工具/03、交叉编译工具/"
        print_info "安装命令: sudo chmod +x atk-dlrk3588-toolchain-*.run && sudo ./atk-dlrk3588-toolchain-*.run"
        exit 1
    fi
    
    # 检查交叉编译器
    CROSS_GCC="$TOOLCHAIN_BIN/${TOOLCHAIN_PREFIX}-gcc"
    if [ ! -f "$CROSS_GCC" ]; then
        print_error "交叉编译器未找到: $CROSS_GCC"
        exit 1
    fi
    
    # 检查交叉编译器版本
    print_info "交叉编译器版本:"
    "$CROSS_GCC" --version | head -1
    
    # 检查sysroot
    if [ ! -d "$TOOLCHAIN_SYSROOT" ]; then
        print_error "Sysroot未找到: $TOOLCHAIN_SYSROOT"
        exit 1
    fi
    
    print_success "交叉编译工具链检查通过"
}

# 检查Qt交叉编译环境
check_qt_cross_environment() {
    print_info "检查Qt交叉编译环境..."
    
    # 检查Qt交叉编译qmake
    if [ ! -f "$QT_CROSS_QMAKE" ]; then
        print_error "Qt交叉编译qmake未找到: $QT_CROSS_QMAKE"
        print_info "请确保交叉编译工具链包含Qt5开发环境"
        exit 1
    fi
    
    # 检查Qt库
    QT_LIB_DIR="$TOOLCHAIN_SYSROOT/usr/lib"
    if [ ! -f "$QT_LIB_DIR/libQt5Core.so" ]; then
        print_warning "Qt5核心库可能未安装在sysroot中"
    fi
    
    # 显示Qt版本信息
    print_info "Qt交叉编译版本信息:"
    "$QT_CROSS_QMAKE" --version
    
    print_success "Qt交叉编译环境检查通过"
}

# 设置交叉编译环境变量
setup_cross_environment() {
    print_info "设置交叉编译环境变量..."
    
    # 设置PATH
    export PATH="$TOOLCHAIN_BIN:$PATH"
    
    # 设置交叉编译器
    export CC="${TOOLCHAIN_PREFIX}-gcc"
    export CXX="${TOOLCHAIN_PREFIX}-g++"
    export AR="${TOOLCHAIN_PREFIX}-ar"
    export STRIP="${TOOLCHAIN_PREFIX}-strip"
    export RANLIB="${TOOLCHAIN_PREFIX}-ranlib"
    
    # 设置编译标志
    export CFLAGS="-O2 --sysroot=$TOOLCHAIN_SYSROOT -fno-builtin -DNO_MATH_VECTOR -D_GNU_SOURCE"
    export CXXFLAGS="-O2 --sysroot=$TOOLCHAIN_SYSROOT -fno-builtin -DNO_MATH_VECTOR -D_GNU_SOURCE -std=c++17"
    export LDFLAGS="--sysroot=$TOOLCHAIN_SYSROOT"
    
    # 设置PKG_CONFIG
    export PKG_CONFIG_PATH="$TOOLCHAIN_SYSROOT/usr/lib/pkgconfig:$TOOLCHAIN_SYSROOT/usr/share/pkgconfig"
    export PKG_CONFIG_SYSROOT_DIR="$TOOLCHAIN_SYSROOT"
    
    print_success "交叉编译环境变量设置完成"
}

# 检查项目依赖
check_dependencies() {
    print_info "检查项目依赖..."
    
    # 检查.pro文件
    if [ ! -f "$PRO_FILE" ]; then
        print_error "未找到项目文件 $PRO_FILE"
        exit 1
    fi
    
    # 检查源代码目录
    if [ ! -d "src" ]; then
        print_error "未找到源代码目录 src/"
        exit 1
    fi
    
    print_success "项目依赖检查完成"
}

# 清理构建目录
clean_build() {
    print_info "清理ARM构建目录..."
    
    if [ -d "$BUILD_DIR" ]; then
        cd $BUILD_DIR
        if [ -f "Makefile" ]; then
            make clean &> /dev/null || true
        fi
        cd ..
        rm -rf $BUILD_DIR
    fi
    
    mkdir -p $BUILD_DIR
    print_success "ARM构建目录已清理"
}

# 生成Makefile
generate_makefile() {
    print_info "使用Qt交叉编译qmake生成Makefile..."
    
    cd $BUILD_DIR
    
    # 创建qmake配置文件
    cat > qt_cross.conf << EOF
# Qt交叉编译配置
QMAKE_CC = ${TOOLCHAIN_PREFIX}-gcc
QMAKE_CXX = ${TOOLCHAIN_PREFIX}-g++
QMAKE_AR = ${TOOLCHAIN_PREFIX}-ar cqs
QMAKE_OBJCOPY = ${TOOLCHAIN_PREFIX}-objcopy
QMAKE_NM = ${TOOLCHAIN_PREFIX}-nm -P
QMAKE_STRIP = ${TOOLCHAIN_PREFIX}-strip

QMAKE_CFLAGS += --sysroot=$TOOLCHAIN_SYSROOT
QMAKE_CXXFLAGS += --sysroot=$TOOLCHAIN_SYSROOT
QMAKE_LFLAGS += --sysroot=$TOOLCHAIN_SYSROOT

# 目标平台
QMAKE_TARGET.arch = aarch64
target.path = /opt/qt_app
INSTALLS += target
EOF
    
    # 使用交叉编译qmake生成Makefile
    if "$QT_CROSS_QMAKE" \
        CONFIG+=release \
        CONFIG-=debug \
        QMAKE_CC=$CC \
        QMAKE_CXX=$CXX \
        QMAKE_LINK=$CXX \
        QMAKE_AR=$AR \
        QMAKE_STRIP=$STRIP \
        QMAKE_CFLAGS+="$CFLAGS" \
        QMAKE_CXXFLAGS+="$CXXFLAGS" \
        QMAKE_LFLAGS+="$LDFLAGS" \
        ../$PRO_FILE; then
        print_success "Makefile生成成功"
    else
        print_error "qmake失败"
        exit 1
    fi
    
    cd ..
}

# 编译项目
compile_project() {
    print_info "交叉编译Qt项目..."
    
    cd $BUILD_DIR
    
    # 获取CPU核心数用于并行编译
    JOBS=$(nproc)
    print_info "使用 $JOBS 个并行任务编译"
    
    # 编译项目
    if make -j$JOBS; then
        print_success "项目交叉编译成功"
    else
        print_error "项目交叉编译失败"
        cd ..
        exit 1
    fi
    
    cd ..
}

# 检查编译结果
check_result() {
    print_info "检查ARM编译结果..."
    
    EXECUTABLE="$BUILD_DIR/$PROJECT_NAME"
    
    if [ -f "$EXECUTABLE" ]; then
        print_success "ARM可执行文件生成成功: $EXECUTABLE"
        
        # 显示文件信息
        print_info "文件信息:"
        ls -lh "$EXECUTABLE"
        
        # 检查文件架构
        print_info "文件架构:"
        file "$EXECUTABLE"
        
        # 检查动态库依赖
        print_info "动态库依赖:"
        ${TOOLCHAIN_PREFIX}-readelf -d "$EXECUTABLE" | grep NEEDED | head -10
        
        # 将ARM可执行文件复制到项目根目录，方便调试/部署
        cp -f "$EXECUTABLE" "./$PROJECT_NAME"
        print_success "已将ARM可执行文件复制到项目根目录: ./$PROJECT_NAME"
        
        return 0
    else
        print_error "ARM可执行文件未生成"
        return 1
    fi
}

# 打包部署文件
package_for_deployment() {
    print_info "打包部署文件..."
    
    EXECUTABLE="$BUILD_DIR/$PROJECT_NAME"
    DEPLOY_DIR="$BUILD_DIR/deploy"
    
    if [ -f "$EXECUTABLE" ]; then
        mkdir -p "$DEPLOY_DIR"
        
        # 复制可执行文件
        cp "$EXECUTABLE" "$DEPLOY_DIR/"
        
        # 复制必要的Qt库
        QT_LIBS=(
            "libQt5Core.so.5"
            "libQt5Gui.so.5"
            "libQt5Widgets.so.5"
            "libQt5Network.so.5"
            "libQt5Multimedia.so.5"
            "libQt5MultimediaWidgets.so.5"
        )
        
        LIB_DIR="$DEPLOY_DIR/lib"
        mkdir -p "$LIB_DIR"
        
        for lib in "${QT_LIBS[@]}"; do
            if [ -f "$TOOLCHAIN_SYSROOT/usr/lib/$lib" ]; then
                cp "$TOOLCHAIN_SYSROOT/usr/lib/$lib" "$LIB_DIR/"
                print_info "复制库: $lib"
            fi
        done
        
        # 创建启动脚本
        cat > "$DEPLOY_DIR/run_app.sh" << 'EOF'
#!/bin/bash
# RK3588智能表情交互系统启动脚本

# 设置库路径
export LD_LIBRARY_PATH="./lib:$LD_LIBRARY_PATH"

# 设置Qt环境
export QT_QPA_PLATFORM=linuxfb
export QT_QPA_FONTDIR=/usr/share/fonts

# 启动应用
./qt_cpp "$@"
EOF
        
        chmod +x "$DEPLOY_DIR/run_app.sh"
        
        # 创建部署说明
        cat > "$DEPLOY_DIR/README.md" << 'EOF'
# RK3588智能表情交互系统部署说明

## 文件说明
- `qt_cpp`: 主程序可执行文件
- `lib/`: Qt运行时库文件
- `run_app.sh`: 启动脚本

## 部署步骤
1. 将整个deploy目录复制到RK3588开发板
2. 在开发板上执行: `chmod +x run_app.sh`
3. 运行程序: `./run_app.sh`

## 系统要求
- RK3588开发板
- Buildroot Linux系统
- 支持Qt5运行环境
EOF
        
        print_success "部署文件打包完成: $DEPLOY_DIR"
        
        # 显示部署目录内容
        print_info "部署目录内容:"
        ls -la "$DEPLOY_DIR"
        
        # 创建部署压缩包
        cd "$BUILD_DIR"
        tar -czf "${PROJECT_NAME}_arm_deploy.tar.gz" deploy/
        print_success "部署压缩包创建完成: $BUILD_DIR/${PROJECT_NAME}_arm_deploy.tar.gz"
        cd ..
    fi
}

# 显示构建摘要
show_summary() {
    print_info "ARM交叉编译构建摘要:"
    echo "=========================================="
    echo "项目名称: $PROJECT_NAME"
    echo "目标平台: ARM64 (aarch64)"
    echo "构建工具: ${TOOLCHAIN_PREFIX}-gcc + Qt交叉编译qmake"
    echo "构建目录: $BUILD_DIR"
    echo "可执行文件: $BUILD_DIR/$PROJECT_NAME"
    echo "根目录可执行文件: ./$PROJECT_NAME"
    echo "部署目录: $BUILD_DIR/deploy"
    echo "部署包: $BUILD_DIR/${PROJECT_NAME}_arm_deploy.tar.gz"
    echo "=========================================="
    
    print_success "ARM Qt项目交叉编译完成！"
    print_info "部署到开发板:"
    print_info "1. scp $BUILD_DIR/${PROJECT_NAME}_arm_deploy.tar.gz root@<board_ip>:/tmp/"
    print_info "2. ssh root@<board_ip>"
    print_info "3. cd /tmp && tar -xzf ${PROJECT_NAME}_arm_deploy.tar.gz"
    print_info "4. cd deploy && ./run_app.sh"
}

# 主函数
main() {
    print_info "开始ARM交叉编译Qt项目 $PROJECT_NAME..."
    print_info "时间: $(date)"
    echo "=========================================="
    
    # 检查参数
    case "${1:-}" in
        "clean")
            clean_build
            print_success "ARM构建目录清理完成"
            exit 0
            ;;
        "check")
            check_toolchain
            check_qt_cross_environment
            check_dependencies
            print_success "ARM交叉编译环境检查完成"
            exit 0
            ;;
        "help"|"-h"|"--help")
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  clean    清理ARM构建目录"
            echo "  check    检查交叉编译环境和依赖"
            echo "  help     显示此帮助信息"
            echo "  (无参数) 完整ARM交叉编译项目"
            echo ""
            echo "交叉编译工具链要求:"
            echo "  - 正点原子ATK-DLRK3588交叉编译工具链"
            echo "  - 安装路径: $TOOLCHAIN_DIR"
            exit 0
            ;;
    esac
    
    # 执行构建步骤
    check_toolchain
    check_qt_cross_environment
    setup_cross_environment
    check_dependencies
    clean_build
    generate_makefile
    compile_project
    
    if check_result; then
        package_for_deployment
        show_summary
    else
        print_error "ARM交叉编译失败"
        exit 1
    fi
}

# 运行主函数
main "$@"
